-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
61 lines (49 loc) · 1.44 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.util.Scanner;
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public class MiddleOfLinkedList {
public static void printList(Node head) {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
}
System.out.println("NULL");
}
public static void findMiddle(Node head) {
Node slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
if (slow != null) {
System.out.println("The middle element is: " + slow.data);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of nodes: ");
int n = scanner.nextInt();
Node head = null, tail = null;
for (int i = 0; i < n; i++) {
System.out.print("Enter value for node " + (i + 1) + ": ");
int value = scanner.nextInt();
Node newNode = new Node(value);
if (head == null) {
head = tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
System.out.println("Original List: ");
printList(head);
findMiddle(head);
}
}